package com.black.knight.chess;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

import com.black.knight.chess.adapters.PGNGameAdapter;
import com.black.knight.chess.domain.Game;
import com.black.knight.chess.domain.PNGGame.PNGGames;
import com.black.knight.chess.domain.PNGOpening.PNGOpenings;
import com.black.knight.chess.domain.PNGProblem.PNGProblems;
import com.black.knight.chess.enums.NewGame;
import com.black.knight.chess.model.PNGGamesModel;
import com.black.knight.chess.model.SahModel;
import com.black.knight.chess.utils.ChessUtil;
import com.black.knight.chess.utils.Utils;
import com.codethesis.pgnparse.PGNGame;
import com.codethesis.pgnparse.PGNParser;

public class PGNGameActivity extends Activity{

	private PGNGameActivity context;
	
	Cursor cursor = null;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        
    	this.context = this;
    	
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        setContentView(R.layout.pgngames);
        
        final ListView gamesList = (ListView) findViewById(R.id.gamesList);
        
        final EditText autoCompleteTextView = (EditText) findViewById(R.id.autocomplete_game);
        autoCompleteTextView.setText(PNGGamesModel.getInstance().getLastSearch());
        
        autoCompleteTextView.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {				
				String lastSearch = PNGGamesModel.getInstance().getLastSearch();
				
				if(s.toString().equals(lastSearch)) return;
				else PNGGamesModel.getInstance().setLastSearch(s.toString());
				
				if(cursor != null) cursor.close();
				
				String cat = ChessUtil.getCategoryName(PNGGamesModel.getInstance().getSelectedCategory());
				
				if("problems".equals(cat)) { 
					cursor = PNGGamesModel.getProblemsLike(PNGProblems.DESCRIPTION + " like '%" + PNGGamesModel.getInstance().getLastSearch() + "%'");
				} else {
					cursor = PNGGamesModel.getGamesLike(PNGGames.DESCRIPTION + " like '%" + s.toString() + "%'", ChessUtil.getCategoryName(PNGGamesModel.getInstance().getSelectedCategory()));
				}
				gamesList.setAdapter(new PGNGameAdapter(context, cursor));
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
        
        final Spinner categoryType = (Spinner) findViewById(R.id.categoryType);
        categoryType.setPrompt(getResources().getString(R.string.choose_category));
        
        final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.category_type, android.R.layout.simple_spinner_item);
        
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        categoryType.setAdapter(adapter);

        categoryType.setSelection(PNGGamesModel.getInstance().getSelectedCategory());
        
        categoryType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {				
				if(cursor != null) cursor.close();
				
				PNGGamesModel.getInstance().setSelectedCategory(arg2);
				
				if("problems".equals(ChessUtil.getCategoryName(arg2))) { 
					cursor = PNGGamesModel.getProblemsLike(PNGProblems.DESCRIPTION + " like '%" + PNGGamesModel.getInstance().getLastSearch() + "%'");
				} else {
					cursor = PNGGamesModel.getGamesLike(PNGGames.DESCRIPTION + " like '%" + PNGGamesModel.getInstance().getLastSearch() + "%'", ChessUtil.getCategoryName(arg2));
				}
				
				gamesList.setAdapter(new PGNGameAdapter(context, cursor));
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
        });
       	
        cursor = PNGGamesModel.getGamesLike(PNGGames.DESCRIPTION + " like '%" + PNGGamesModel.getInstance().getLastSearch() + "%'", ChessUtil.getCategoryName(PNGGamesModel.getInstance().getSelectedCategory()));
        
        if(cursor == null || cursor.isClosed()) {
        	context.finish();
	    	SahModel.context.finish();
        	Intent intent = new Intent();
        	intent.setClass(SahModel.context, SahMatActivity.class);
        	SahModel.context.startActivity(intent);
        	return;
        }
        
       	gamesList.setAdapter(new PGNGameAdapter(context, cursor));
       	
       	registerForContextMenu(gamesList);
       	
       	gamesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int position, long posigion1) {
				CursorAdapter adapter = (CursorAdapter)adapterView.getAdapter();
				Cursor cursor = adapter.getCursor();
				
				String cat = ChessUtil.getCategoryName(PNGGamesModel.getInstance().getSelectedCategory());
	    	  	
	    	  	if("problems".equals(cat)) {
	    	  		solveProblem(cursor, position);
	    	  	} else {
	    	  		showGame(cursor, position);
	    	  	}
			}
		});
    }
    
    private void solveProblem(Cursor cursor, int position) {
    	cursor.moveToPosition(position);
		
		String fen = cursor.getString(cursor.getColumnIndex(PNGProblems.FEN));
		
		Integer mateIn = cursor.getInt(cursor.getColumnIndex(PNGProblems.MATE_IN));
		
		context.finish();
		
		SahModel.context.solveProblem(fen, mateIn);
    }
    
    private void showGame(Cursor cursor, int position) {
		cursor.moveToPosition(position);
		
		String pgn = cursor.getString(cursor.getColumnIndex(PNGOpenings.PNG));
		
		String fen = cursor.getString(cursor.getColumnIndex(PNGOpenings.FEN));
		
		try {
			PNGGamesModel.getInstance().setCurrentGame(PGNParser.parsePGNGame(pgn, fen));
			
			String white = "White";
			String black = "Black";
			
			if(PNGGamesModel.getInstance().getCurrentGame().getTags().containsKey("White")) {
    			white = PNGGamesModel.getInstance().getCurrentGame().getTags().get("White");
    		}
			
			if(PNGGamesModel.getInstance().getCurrentGame().getTags().containsKey("Black")) {
    			black = PNGGamesModel.getInstance().getCurrentGame().getTags().get("Black");
    		}
			
			if(PNGGamesModel.getInstance().getCurrentGame().isEndGameMarked()) {
    	    	context.finish();
    	    	
    	    	SahModel.getInstance().reset(fen);
    	    	Game game = SahModel.getInstance().getGame();
    	    	game.setPlayOnClock(false);
    	    	
    	    	game.getPlayer1().setName(white);
    	    	game.getPlayer2().setName(black);
    	    	
    	    	game.setMoves(PNGGamesModel.getInstance().getCurrentGame().toMoves());
    	    	
    	    	SahModel.context.playNewGame(NewGame.ANALIZE, false);
			} else {
				context.finish();
				
				Utils.chooseNewGameType(SahModel.context, fen, white, black, PNGGamesModel.getInstance().getCurrentGame().toMoves());
			}		
		} catch (Exception e) {
			Utils.displayToastMessage(context, "Cannot parse pgn game!");
		}
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	      if (v.getId()==R.id.gamesList) {
	    	  	AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
	    	  	
	    	  	final ListView gamesList = (ListView) findViewById(R.id.gamesList);
	    	  	
	    	  	Cursor cursor = (Cursor)gamesList.getAdapter().getItem(info.position);
	    	  	
	    	  	menu.setHeaderTitle(cursor.getString(cursor.getColumnIndex(PNGGames.DESCRIPTION)));
	    	    
	    	  	String cat = ChessUtil.getCategoryName(PNGGamesModel.getInstance().getSelectedCategory());
	    	  	
	    	  	if("problems".equals(cat)) {
	    	  		menu.add(Menu.NONE, 0, 0, context.getResources().getString(R.string.solve));
	    	  	} else if("my_games".equals(cat)) {
	    	  		menu.add(Menu.NONE, 0, 0, context.getResources().getString(R.string.open));
	    	  		menu.add(Menu.NONE, 0, 0, context.getResources().getString(R.string.edit));
	    	  		menu.add(Menu.NONE, 0, 0, context.getResources().getString(R.string.delete));
	    	  	} else {
	    	  		menu.add(Menu.NONE, 0, 0, context.getResources().getString(R.string.open));
	    	  	}
	      }
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
	      AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
	      
	      if(item.getTitle().equals(context.getResources().getString(R.string.solve))) {
	    	  solveProblem(cursor, info.position);
	      }
	
	      final ListView gamesList = (ListView) findViewById(R.id.gamesList);
	      Cursor cursor = (Cursor)gamesList.getAdapter().getItem(info.position);
	      
	      if(item.getTitle().equals(context.getResources().getString(R.string.open))) {
	    	  showGame(cursor, info.position);
	      } else if(item.getTitle().equals(context.getResources().getString(R.string.edit))) {
	    	  cursor.moveToPosition(info.position);
	  		  String pgn = cursor.getString(cursor.getColumnIndex(PNGOpenings.PNG));
	  		  String fen = cursor.getString(cursor.getColumnIndex(PNGOpenings.FEN));
	  		  
	  		  try {
	  			  PGNGame pgnGame = PGNParser.parsePGNGame(pgn, fen);
	  			  SahModel.getInstance().getGame().setPgnGameString(pgnGame.toString());
	  			  SahModel.getInstance().setFenString(fen);
	  			  
	  			  PNGGamesModel.getInstance().setTags(pgnGame.getTags());
	  			  
		    	  Intent intent2 = new Intent();
		    	  intent2.setClass(this, AddPGNGameActivity.class);
		    	  startActivity(intent2);
		    	  
		    	  finish();
	  		  } catch (Exception e) { }
	      } else if(item.getTitle().equals(context.getResources().getString(R.string.delete))) {
	    	  PNGGamesModel.deleteGame(cursor.getInt(cursor.getColumnIndex(PNGGames.PNG_GAME_ID)));
	      }
	      
	      return true;
    }
    
	@Override
	protected void onDestroy() {
		cursor.close();
		
		super.onDestroy();
	}
}